let form = layui.form
// 剪裁效果
let image = $('#image')
let option = {
    aspectRatio: 400 / 280,
    preview: '.img-preview',
    autoCropArea: 1
}
image.cropper(option)
// 获取地址栏的id
let id = new URLSearchParams(location.search).get('id')
// 获取分类，熏染
$.ajax({
    url: '/my/category/list',
    success: function (res) {
        let arr = []
        res.data.forEach(item => {
            arr.push(`<option value='${item.id}'>${item.name}</option>`)
        })
        $('select[name=cate_id]').append(arr.join(""))
        // 更新渲染
        form.render('select')

        // 保证下拉框渲染完再数据回填
        $.ajax({
            url: '/my/article/' + id,
            success: function (res) {
                form.val('bj', res.data)

                // 把textarea插件调用
                initEditor()
                // 单独回填图片
                image.cropper('destroy').attr('src', baseUrl + '/' + res.data.cover_img).cropper(option)
            }
        })
    }
})
// 点击按钮触发单机事件
$('button:contains("选择封面")').on('click', function () {
    $('#file').trigger('click')
})

// 当文件域内容改变，更换图片
$('#file').on('change', function () {
    let files = this.files
    let url = URL.createObjectURL(files[0])
    image.cropper('destroy').attr('src', url).cropper(option)
})
// 表单提交，阻止默认，收集，ajax
$('form').on('submit', function (e) {
    e.preventDefault()
    let fd = new FormData(this)//传入dom
    // 修改fd里的content
    fd.set('content', tinyMCE.activeEditor.getContent())
    // 剪裁图片
    let canvas = image.cropper('getCroppedCanvas', {
        width: 400,
        height: 280
    })
    // 检查fd数据
    canvas.toBlob(function (blob) {
        fd.append('cover_img', blob)
        fd.append('id', id)
        $.ajax({
            type: 'POST',
            url: '/my/article/update',
            data: fd,
            processData: false,
            contentType: false,
            success: function (res) {
                layer.msg(res.message)
                if (res.status === 0) {
                    location.href = './list.html'
                }
            }
        })
    })
})
